<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="缺陷描述">
          <el-input v-model="searchForm.flawDesc" placeholder="请输入缺陷描述" clearable />
        </el-form-item>
        <el-form-item label="检测项类型">
          <el-select v-model="searchForm.detectType" placeholder="请选择检测项类型" clearable>
            <el-option v-for="item in inspectionTypes" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷等级">
          <el-select v-model="searchForm.flawGrade" placeholder="请选择缺陷等级" clearable>
            <el-option v-for="item in defectLevels" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮工具栏 -->
    <div class="button-container">
      <el-button type="primary" class="custom-button add-button" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增
      </el-button>
      <el-button 
        type="danger" 
        class="custom-button delete-button" 
        @click="handleBatchDelete" 
        :disabled="selectedRows.length === 0"
      >
        <el-icon><Delete /></el-icon>删除
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      border
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="flawDesc" label="缺陷描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="detectType" label="检测项类型" min-width="120" show-overflow-tooltip />
      <el-table-column prop="flawGrade" label="缺陷等级" min-width="120" align="center" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" link @click="handleSingleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '修改常见缺陷' : '添加常见缺陷'"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
        class="form"
      >
        <el-form-item label="缺陷描述" prop="flawDesc">
          <el-input
            v-model="form.flawDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入缺陷描述"
          />
        </el-form-item>
        
        <el-form-item label="检测项类型" prop="detectType">
          <el-select v-model="form.detectType" placeholder="请选择检测项类型" style="width: 100%">
            <el-option v-for="item in inspectionTypes" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="缺陷等级" prop="flawGrade">
          <el-select v-model="form.flawGrade" placeholder="请选择缺陷等级" style="width: 100%">
            <el-option v-for="item in defectLevels" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
import http from '@/api/http'

// 检测项类型选项
const inspectionTypes = [
  '成型',
  '轴验',
  '烧成',
  '尺寸',
  '外观',
  '重量',
  '性能',
  '成分'
]

// 缺陷等级选项
const defectLevels = [
  '致命缺陷',
  '严重缺陷',
  '轻微缺陷'
]

// 搜索表单数据
const searchForm = reactive({
  flawDesc: '',
  detectType: '',
  flawGrade: ''
})

// 表单数据
const form = reactive({
  id: 0,
  flawDesc: '',
  detectType: '',
  flawGrade: ''
})

// 表单校验规则
const formRules = {
  flawDesc: [
    { required: true, message: '请输入缺陷描述', trigger: 'blur' }
  ],
  detectType: [
    { required: true, message: '请选择检测项类型', trigger: 'change' }
  ],
  flawGrade: [
    { required: true, message: '请选择缺陷等级', trigger: 'change' }
  ]
}

// 页面状态数据
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const submitLoading = ref(false)
const selectedRows = ref([])
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取表格数据
const fetchData = async () => {
  loading.value = true
  try {
    const queryParams = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      FlawDesc: searchForm.flawDesc?.trim() || '',
      DetectType: searchForm.detectType || '',
      FlawGrade: searchForm.flawGrade || ''
    }

    console.log('查询参数:', queryParams)
    const response = await http.get('/api/Flaws/QueryFlawsList', { params: queryParams })
    console.log('API响应:', response)
    
    // 检查返回数据结构
    if (response && response.data && Array.isArray(response.data.items)) {
      // 转换数据为前端格式
      tableData.value = response.data.items.map(item => ({
        id: item.Id,
        flawDesc: item.FlawDesc,
        detectType: item.DetectType,
        flawGrade: item.FlawGrade
      }))
      total.value = response.data.total || 0
    } else {
      console.error('返回数据格式不正确:', response)
      throw new Error('返回数据格式不正确')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败：' + (error.message || '未知错误'))
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.flawDesc = ''
  searchForm.detectType = ''
  searchForm.flawGrade = ''
  handleSearch()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    form.id = 0
    form.flawDesc = ''
    form.detectType = ''
    form.flawGrade = ''
  }
}

// 打开添加对话框
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  nextTick(() => {
    resetForm()
  })
}

// 编辑
const handleEdit = (row) => {
  console.log('编辑行数据:', row)
  isEdit.value = true
  dialogVisible.value = true
  nextTick(() => {
    // 确保字段名匹配
    form.id = row.Id || row.id
    form.flawDesc = row.FlawDesc || row.flawDesc
    form.detectType = row.DetectType || row.detectType
    form.flawGrade = row.FlawGrade || row.flawGrade
    
    // 打印表单数据，用于调试
    console.log('表单数据:', form)
  })
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除这条记录吗？', '提示', {
      type: 'warning'
    })
    
    const response = await http.post(`/api/Flaws/BatchDeleteFlaws?ids=${row.id}`)
    
    if (response?.status === true) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      throw new Error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      handleDelete(selectedRows.value[0])
    })
    .catch(() => {
      // 取消删除
    })
}

// 单个删除
const handleSingleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这条记录吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      handleDelete(row)
    })
    .catch(() => {
      // 取消删除
    })
}

// 表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 转换为后端需要的格式
        const submitData = {
          Id: form.id,
          FlawDesc: form.flawDesc,
          DetectType: form.detectType,
          FlawGrade: form.flawGrade
        }
        
        const url = isEdit.value 
          ? '/api/Flaws/UpdateFlaws'
          : '/api/Flaws/AddFlaws'
          
        console.log('提交数据:', submitData)
        const response = await http.post(url, submitData)
        console.log('提交响应:', response)
        
        if (response?.status === true) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          dialogVisible.value = false
          fetchData()
        } else {
          throw new Error(response?.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败: ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭时重置表单
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.keys(form).forEach(key => {
    if (key === 'id') {
      form[key] = 0
    } else {
      form[key] = ''
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.button-container {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.custom-button {
  border-radius: 4px;
  padding: 8px 15px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  border: none;
}

.custom-button .el-icon {
  margin-right: 4px;
}

.add-button {
  background-color: #ecf5ff;
  color: #409EFF;
}

.add-button:hover {
  background-color: #409EFF;
  color: #fff;
}

.delete-button {
  background-color: #fef0f0;
  color: #F56C6C;
}

.delete-button:hover {
  background-color: #F56C6C;
  color: #fff;
}

.delete-button[disabled] {
  background-color: #f5f7fa !important;
  color: #c0c4cc !important;
  cursor: not-allowed;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-button--link) {
  padding: 2px 4px;
}
</style> 